package frame.util.generator;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class GeneratMySql extends Generator {


    private static final Map<String,Class<?>> jdbc2java;

    static {
        jdbc2java = new HashMap<>();

        jdbc2java.put("BIT", Byte.class);
        jdbc2java.put("TINYINT", Byte.class);
        jdbc2java.put("TINYINT UNSIGNED", Byte.class);

        jdbc2java.put("INT", Integer.class);
        jdbc2java.put("INT UNSIGNED", Integer.class);
        jdbc2java.put("BIGINT", Long.class);

        jdbc2java.put("FLOAT", Float.class);
        jdbc2java.put("DOUBLE", Double.class);

        jdbc2java.put("VARCHAR", String.class);
        jdbc2java.put("CHAR", String.class);
        jdbc2java.put("TEXT", String.class);
        jdbc2java.put("ENUM", String.class);

        jdbc2java.put("TIME", Date.class);
        jdbc2java.put("TIMESTAMP", Date.class);
        jdbc2java.put("DATETIME", Date.class);
    }


    @Override
	protected void init() {
		showSuccess("-> GeneratMySql 创建成功，即将执行基于Mybatis通用Mapper的逆向工程-_-");
	}

    @Override
    protected void convertTable2Entity() {
        try {
            DatabaseMetaData meta = super.connection.getMetaData();
            ResultSet rs = meta.getColumns(null, "%", configure.getTableName(), "%");
            /*
            ResultSetMetaData metaData = rs.getMetaData();
            String[] datas = new String[metaData.getColumnCount()];
            // 查看全部列属性
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                System.out.println(i + " -- " +metaData.getColumnName(i));
                datas[i-1] = metaData.getColumnName(i);
            }
            */
            while(rs.next()){
                Column2Field c2f = convertColumn2Field(rs);
                if ("id".equals(rs.getString("REMARKS"))) {
					//System.out.println("找到主键：" + columnName);
					id = c2f;
				} else if (!superColumnSet.contains(c2f.getColumnName())) {
					fieldList.add(c2f);
				}
            }
            StringBuilder sb = new StringBuilder("数据表字段解析成功：");
            if (id == null)
            	sb.append("\n\tid:").append("无");
            else
            	sb.append("\n\tid:").append(id.getColumnName()).append(" ").append(id.getColumnType()).append("(").append(id.getColumnSize()).append(") -> ")
            	.append(id.getFieldType()).append(" ").append(id.getFieldName());
            for (Column2Field c2f : fieldList) {
				sb.append("\n\t|-\t").append(c2f.getColumnName()).append(" ").append(c2f.getColumnType()).append("(").append(c2f.getColumnSize()).append(")\t=> ")
            	.append(c2f.getFieldType()).append(" ").append(c2f.getFieldName());
			}
            showSuccess(sb.toString());
        } catch (SQLException e) {
            runAble = false;
            showError("数据表字段解析失败，流程终止！", e, false);
        }
    }

    @Override
    protected void convertColumnNameSqlList() {
        StringBuilder sb = new StringBuilder();
        for (Column2Field c2f : fieldList) {
            sb.append("t.").append(c2f.getColumnName()).append(",");
        }
        for (Column2Field c2f : superFieldList) {
            sb.append("t.").append(c2f.getColumnName()).append(",");
        }
        sb.append("t.").append(id.getColumnName());
        super.columnNameSqlList = sb.toString();
    }

    private Column2Field convertColumn2Field(ResultSet rs) throws SQLException {
        //列名
        String columnName = rs.getString("COLUMN_NAME");
        //类型
        String typeName = rs.getString("TYPE_NAME");
        //注释
        String remarks = rs.getString("REMARKS");
        //长度
        int size = rs.getInt("COLUMN_SIZE");
        Class<?> clazz = convoterClass(typeName,size);
        addImport(clazz);
        //System.out.println("COLUMN_NAME:"+columnName + "--TYPE_NAME:" + typeName + "--REMARKS:" + remarks + "--size:" + size );

        Column2Field c2f = new Column2Field();

        c2f.setColumnName(columnName);
        c2f.setColumnType(typeName);
        c2f.setColumnSize(size);
        c2f.setRemarks(remarks);

        c2f.setFieldName(Generator.lineToHump(columnName));
        c2f.setFieldType(clazz.getSimpleName());
        return c2f;
    }

    private Class<?> convoterClass(String jdbcType, int size) {
    	Class<?> clazz = jdbc2java.getOrDefault(jdbcType, Object.class);
    	if (clazz == Integer.class && size > 11) {
    		clazz = Long.class;
		}
    	return clazz;
    }
    private void addImport(Class<?> clazz) {
    	if (clazz == Date.class) {
    		entityImportSet.add(Date.class.getName());
		}
    }


}
